<?php
namespace app\api\controller;

use app\admin\controller\Basic\model\Driver as DriverModel;
use app\admin\controller\Basic\model\ShiftSite;
use app\admin\controller\Basic\model\ShiftVehicle;
use app\BaseController;
use think\App;
use think\exception\ValidateException;
use app\api\model\User as UserModel;
use app\api\model\UserToken as UserTokenModel;
use app\api\model\UserPassenger as UserPassengerModel;
use app\api\model\Order as OrderModel;
use app\api\service\UserService;
use utils\wechart\WxuserService;
use think\facade\Db;

class User extends BaseController
{
    // protected $middleware = [ 
    // 	'auth' 	=> ['except' 	=> ['hello'] ],//除了hello方法，其它方法都验证
    //   check' => ['only' 		=> ['hello'] ],//只有hello方法验证，其它方法都不用
    // ];
    protected $middleware = [
        'token' => ['except' => ['testLogin', 'login', 'bindMobile']]
    ];
    protected $userInfo = [];

    public function __construct(App $app, \think\View $view)
    {
        parent::__construct($app, $view);
        $this->userInfo = getUserId();
    }

    public function testLogin() 
    {
        $token = '123131231';
        $userInfo = [
            'user_id' => '2',
            'nickname' => '微信用户',
            'avatar' => '12313',
            'openid' => 'okvtt5aO1ejRcP4W1KAhEDn3ITfw',
        ];
        cache('user_token'.$token, $userInfo ,['expire' => 86400 * 3]);
        var_dump($userInfo);exit;
    }

    public function info() 
    {
        $config = Db::table('bs_base_config')
                            ->where('name','service')
                            ->whereOr('name', 'privacy')
                            ->whereOr('name', 'customer_service')
                            ->field('name,data')
                            ->select()
                            ->toArray();
        if ($config) {
            foreach ($config as $k=> $rs) {
                if ($rs['name'] == 'customer_service') {
                    $config[$k]['data'] = json_decode($rs['data'], true);
                }
            }
        }
        $data['status'] = 200;
		$data['data'] = [
            'user_info' => $this->userInfo,
            'config' => $config
        ];
		return json($data);
    }

    public function login() 
    {
        $validate = validate([
            'fid' => 'require',
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require'
        ], [
            'code.require'=>'code不存在',
            'iv.require'=>'iv不存在',
            'fid.require'=>'fid不存在',
            'encryptedData.require'=>'encryptedData不存在'
        ], false, false);
        $post = $this->request->param();
        $result = $validate->check($post);
        if (!$result) {
            $error = $validate->getError();
            return msg(0, $error);
        }
        $res = WxuserService::getXcxUserInfo($post);
        if (isset($res['code']) && $res['code'] == 0) {
            throw new ValidateException ($res['msg']);
        }
        $res['fid'] = $post['fid'];
        $userInfo = UserService::getInstance()->loginOrtempRegister($res);
        $data['status'] = 200;
		$data['data'] = $userInfo;
		return json($data);
    } 

    public function bindMobile() 
    {
        $validate = validate([
            'fid' => 'require',
            'openid' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'openid.require'=>'openid不存在',
            'iv.require'=>'iv不存在',
            'fid.require'=>'fid不存在',
            'encryptedData.require'=>'encryptedData不存在'
        ], false, false);
        $post = $this->request->param();
        $result = $validate->check($post);
        if (!$result) {
            $error = $validate->getError();
            return msg(0, $error);
        }
       // $post['openid'] = $this->userInfo['openid'];
        $res = WxuserService::getXcxUserInfo($post);
        if (isset($res['code']) && $res['code'] == 0) {
            throw new ValidateException ($res['msg']);
        }
        $userInfo = UserService::getInstance()->registerAndBindMobile($post['openid'], $res);
        $data['status'] = 200;
        $data['msg'] = '登录成功';
		$data['data'] = $userInfo;
		return json($data);
    }

    public function passengerList() 
    {
        $limit  = $this->request->get('limit', 20, 'intval');
		$page = $this->request->get('page', 1, 'intval');
        $where = [
            'user_id' => $this->userInfo['user_id'],
            'status' => 1,
        ];
        $userList = UserPassengerModel::where($where)
                    ->field('id,name,identity_type,identity_no,mobile')
                    ->paginate(['list_rows'=>$limit,'page'=>$page])
                    ->toArray();
        $data['status'] = 200;
        $data['data'] = $userList;
        return json($data);
    }

    public function passengerInfo() 
    {
        $id = $this->request->get('id', 0, 'intval');
        $where = [
            'user_id' => $this->userInfo['user_id'],
            'id' => $id,
        ];
        $userInfo = UserPassengerModel::where($where)->field('id,name,identity_type,identity_no,mobile')->find();
        $data['status'] = 200;
        $data['data'] = $userInfo;
        return json($data);
    }

    public function addPassenger() {
        $postField = 'name,identity_type,identity_no,mobile';
		$postData = $this->request->only(explode(',',$postField),'post',null);
		$this->validate($postData,\app\api\validate\User::class);
        $insert = [
            'user_id' => $this->userInfo['user_id'],
            'name' => $postData['name'],
            'identity_type' => $postData['identity_type'],
            'identity_no' => $postData['identity_no'],
            'mobile' => $postData['mobile'],
            'create_time' => time()
        ];
        if (!checkIdentityNo($postData['identity_no'])) {
            throw new ValidateException ('身份证号错误');
        }
        $where = [
            'user_id' => $this->userInfo['user_id'],
            'identity_no' => $postData['identity_no'],
        ];
        $info = UserPassengerModel::where($where)->find();
        if ($info) {
            throw new ValidateException ('证件号码已存在');
        }
        $res = UserPassengerModel::create($insert);
        if (!$res) {
            throw new ValidateException ('添加失败');
        }
        $data['status'] = 200;
		$data['data'] = [
            'id' => $res->id
        ];
		return json($data);
    }

    public function editPassenger()
    {
        $postField = 'id,name,identity_type,identity_no,mobile';
		$postData = $this->request->only(explode(',',$postField),'post',null);
		$this->validate($postData,\app\api\validate\User::class);
        $update = [
            'user_id' => $this->userInfo['user_id'],
            'name' => $postData['name'],
            'identity_type' => $postData['identity_type'],
            'identity_no' => $postData['identity_no'],
            'mobile' => $postData['mobile'],
            'create_time' => time()
        ];
        if (!checkIdentityNo($postData['identity_no'])) {
            throw new ValidateException ('身份证号错误');
        }
        $where = [
            'user_id' => $this->userInfo['user_id'],
            'id' => $postData['id'],
        ];
        $info = UserPassengerModel::where($where)->find();
        if (!$info) {
            throw new ValidateException ('数据不存在');
        }
        $where2 = [
            'user_id' => $this->userInfo['user_id'],
            'identity_no' => $postData['identity_no'],
        ];
        $info2 = UserPassengerModel::where($where2)->find();
        if ($info2 && $info2->id != $postData['id']) {
            throw new ValidateException ('证件号码已存在');
        }
        $res = UserPassengerModel::where($where)->update($update);
        if ($res === false) {
            throw new ValidateException ('编辑失败');
        }
        $data['status'] = 200;
		$data['data'] = [
            'id' => $info->id
        ];
		return json($data);
    }

    public function historyBuy() 
    {
        $where = [
            'o.buy_user_id' => $this->userInfo['user_id']
        ];
        $order = OrderModel::alias('o')
                    ->leftjoin('site s', 'o.up_site_id=s.id')
                    ->leftjoin('site s1', 'o.down_site_id=s1.id')
                    ->field('o.id,o.line_id,s.name up_site_name,s1.name down_site_name')
                    ->where($where)
                    ->order('o.id', 'desc')
                    ->paginate(['list_rows'=>3,'page'=>1])
                    ->toArray();
        $data['status'] = 200;
		$data['data'] = [
            'list' => $order
        ];
		return json($data);
    }

    /**
     * @return void
     * 司机端班次订单数据
     */
    public function shiftOrderData()
    {
        $order = [];
        $listData = [];
        $date = strtotime(date('Y-m-d'));
        $mobile = $this->userInfo['mobile'];
        $vehicle = DriverModel::alias('d')
                ->leftjoin('vehicle v', 'd.id=v.driver_id')
                ->where('d.mobile','=',$mobile)->field('v.id')->find();
        if ($vehicle) {
            $vehicle = $vehicle->toArray();
            $shiftVehicle = ShiftVehicle::alias('sv')
                ->leftjoin('shift s', 'sv.shift_id=s.id')
                ->leftjoin('line l', 's.line_id=l.id')
                ->where('sv.vehicle_id','=',$vehicle['id'])
                ->where('s.date', '=', $date)
               // ->where('s.start_time', '>', date('H:i:s'))
                ->where('l.status', '=', 1)
                ->field('s.id,s.line_id,l.name line_name,s.start_time')
                ->select()
                ->toArray();
            $shiftid = array_column($shiftVehicle, 'id');
            $lineid = array_column($shiftVehicle, 'line_id');
            $shiftSite = ShiftSite::where('shift_id', 'in', $shiftid)
                ->field('shift_id,site_id,site_name')->select()->toArray();
            $sihftSiteList = [];
            if ($shiftSite) {
                foreach ($shiftSite as $rs) {
                    $sihftSiteList[$rs['shift_id']][$rs['site_id']] = [
                        'site_id' => $rs['site_id'],
                        'site_name' => $rs['site_name']
                    ];
                }
            }
            $orderData = [];
            $order = OrderModel::where('line_id', 'in', $lineid)
                        ->where('shift_id', 'in', $shiftid)
                        ->where('status', '>', 0)
                        ->field('id,line_id,shift_id,up_site_id,count(1) count')
                        ->group('line_id,shift_id,up_site_id')
                        ->select()
                        ->toArray();
            if ($order) {
                foreach ($order as $rs) {
                    $orderData[$rs['line_id']][$rs['shift_id']][$rs['up_site_id']] = [
                        'count' =>$rs['count'],
                        'site_id' => $rs['up_site_id'],
                        'site_name' => $sihftSiteList[$rs['shift_id']][$rs['up_site_id']]['site_name']
                    ];
                }
            }
            foreach ($shiftVehicle as $rs) {
                if (!empty($orderData[$rs['line_id']][$rs['id']])) {
                    $listData[$rs['line_id']]['line_id'] = $rs['line_id'];
                    $listData[$rs['line_id']]['line_name'] = $rs['line_name'];
                    $listData[$rs['line_id']]['shift'][$rs['id']] = [
                        'start_time' => $rs['start_time'],
                        'shift_id' =>$rs['id'],
                        'list' => array_values($orderData[$rs['line_id']][$rs['id']])
                    ];
                }
            }
        }

        $data['status'] = 200;
        $data['data'] = [
            'list' => array_values($listData),
            'date' => date('Y年m月d日')
        ];
        return json($data);
    }
}
